//
//  QuotationCollectionViewController.m
//  RedManStock
//
//  Created by lanou3g on 15/7/25.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "QuotationCollectionViewController.h"
#import "Q1CollectionViewCell.h"
#import "Q2CollectionViewCell.h"
#import "Q3CollectionViewCell.h"
#import "AFNetworking.h"
#import "MyHandle.h"
#import "MarketIndex.h"
#import "HotConcepts.h"
#import "HotIndustries.h"
#import "UpList.h"
#import "DownList.h"
#import "TurnoverList.h"
#import "MJRefresh.h"
#import "MarketIndexDetailTVC.h"
#import "HotIndustriesDetailVC.h"
#import "BangViewController.h"
#import "StockHomeViewController.h"
#import "StockSearchResultTVC.h"
#import "MBProgressHUD.h"
@interface QuotationCollectionViewController ()<UICollectionViewDelegateFlowLayout>

@property(nonatomic,retain)NSMutableArray *marketIndexArray;
@property(nonatomic,retain)NSMutableArray *hotConceptsArray;
@property(nonatomic,retain)NSMutableArray *hotIndustriesArray;
@property(nonatomic,retain)NSMutableArray *upListArray;
@property(nonatomic,retain)NSMutableArray *downListArray;
@property(nonatomic,retain)NSMutableArray *turnverListArray;
//定义各异整型属性，用于传给深沪大盘详情，用于下方开始的时候是显示1对应的涨幅榜
@property(nonatomic,assign)NSInteger num;
@end

@implementation QuotationCollectionViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    UIBarButtonItem *searchButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchBarButtonAction:)];
    self.parentViewController.navigationItem.rightBarButtonItem = searchButton;
    
//初始化数据源们
    self.marketIndexArray = [NSMutableArray array];
    self.hotConceptsArray = [NSMutableArray array];
    self.hotIndustriesArray = [NSMutableArray array];
    self.upListArray = [NSMutableArray array];
    self.downListArray = [NSMutableArray array];
    self.turnverListArray = [NSMutableArray array];
#pragma mark - 用Nib文件注册cell -
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.collectionView registerNib:[UINib nibWithNibName:@"Q1CollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"Q1"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"Q2CollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"Q2"];

 [self.collectionView registerNib:[UINib nibWithNibName:@"Q3CollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"Q3"];
    
//    注册页眉
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    

    //设置刷新头或刷新尾
   
        MJRefreshGifHeader *header=[MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        
        //        NSMutableArray *idleArray=[NSMutableArray array];
        NSMutableArray *pullingArray=[NSMutableArray array];
        NSMutableArray *refreshArray=[NSMutableArray array];
        NSMutableArray *doneArray=[NSMutableArray array];
        
        for (int i=0; i<=140; i++) {
            NSString *placeStr=[NSString string];
            if (i<10) {
                placeStr=[NSString stringWithFormat:@"00%d",i];
            }
            else if(i>=10 && i<100){
                placeStr=[NSString stringWithFormat:@"0%d",i];
            }
            else{
                placeStr=[NSString stringWithFormat:@"%d",i];
            }
            
            NSString *imageName=[NSString stringWithFormat:@"PullToRefresh_%@",placeStr];
            UIImage *image=[UIImage imageNamed:imageName];
            if (i<=73) {
                [pullingArray addObject:image];
            }
            else if(i>73 && i<=127){
                [refreshArray addObject:image];
            }
            else{
                [doneArray addObject:image];
            }
            
        }
        
        [header setImages:pullingArray forState:MJRefreshStatePulling];
        [header setImages:refreshArray forState:MJRefreshStateRefreshing];
        [header setImages:doneArray forState:MJRefreshStateNoMoreData];
        
        header.lastUpdatedTimeLabel.hidden=YES;
        header.stateLabel.hidden=YES;
        
        self.collectionView.header=header;
    
    
    [self loadNewData];
        
    }

//
-(void)searchBarButtonAction:(UIBarButtonItem *)searchBarButton{
    
    StockSearchResultTVC *stockSearchTVC=[[StockSearchResultTVC alloc]init];
    UISearchController *searchController=[[UISearchController alloc]initWithSearchResultsController:stockSearchTVC];
    stockSearchTVC.searchController=searchController;
    [self.parentViewController presentViewController:searchController animated:YES completion:nil];
    
}



    
#pragma mark- 刷新方法，完成拼接网址 -
-(void)loadNewData{
    
    //    出现大菊花
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    http://api.gongniucaijing.com/quotation/index ?idfa=7B7C9B42-5C18-4EEB-A0F8-6708DE081AAE&machine=iPhone%205&os=iPhone%20OS%208.2&platform=1&protocolVersion=1.0&qudao=0000001&resolution=640%2A1136&token=d58f02522dac7e698a4600c8b18ff02c0b9fa6df&uuid=BULLSTOCK-79460017-C3E5-45EC-B98C-1DD541A61127&version=1.9.0&versionCode=190
    
    
    NSString *urlStr = @"http://api.gongniucaijing.com/quotation/index";
    [[MyHandle new] requestDataWithURLStr:urlStr parameterBlock:^NSDictionary *{
        

        NSDictionary *dic=@{@"token":@"d58f02522dac7e698a4600c8b18ff02c0b9fa6df"};
        return dic;
    } successBlock:^(NSDictionary *responseDic) {
//        现将数据源清空
//        [self.marketIndexArray removeAllObjects];
        
        NSDictionary *dic = responseDic;
        NSDictionary *dataDic = [dic objectForKey:@"data"];
        NSDictionary *marketIndexDic = [dataDic objectForKey:@"marketIndex"];
        NSArray *listsArray1 = [marketIndexDic objectForKey:@"lists"];
        [self.marketIndexArray removeAllObjects];
        for (NSDictionary *dic in listsArray1) {
            
            MarketIndex *marketIndex = [[MarketIndex alloc]init];
            [marketIndex setValuesForKeysWithDictionary:dic];
//            给数据源赋值
            [self.marketIndexArray addObject:marketIndex];
            
            
        }
        
        NSDictionary *hotIndustriesDic = [dataDic objectForKey:@"hotIndustries"];
        NSArray *listsArray2 = [hotIndustriesDic objectForKey:@"lists"];
        [self.hotIndustriesArray removeAllObjects];
        for (NSDictionary *dic in listsArray2) {
            
            HotIndustries *hotIndustries = [[HotIndustries alloc]init];
            [hotIndustries setValuesForKeysWithDictionary:dic];
//            给数据源赋值
            [self.hotIndustriesArray addObject:hotIndustries];
            
            
            
        }
        
        NSDictionary *hotConceptsDic = [dataDic objectForKey:@"hotConcepts"];
        NSArray *listsArray3 = [hotConceptsDic objectForKey:@"lists"];
        [self.hotConceptsArray removeAllObjects];
        for (NSDictionary *dic in listsArray3) {
            
            HotConcepts *hotConcepts = [[HotConcepts alloc]init];
            [hotConcepts setValuesForKeysWithDictionary:dic];
            
            [self.hotConceptsArray addObject:hotConcepts];
            
        }
        
        NSDictionary *upListdic = [dataDic objectForKey:@"upList"];
        NSArray *listsArray4 = [upListdic objectForKey:@"lists"];
        [self.upListArray removeAllObjects];
        for (NSDictionary *dic in listsArray4) {
            UpList *upList = [[UpList alloc]init];
            [upList setValuesForKeysWithDictionary:dic];
            
            [self.upListArray addObject:upList];
            
        }
        
        NSDictionary *downListDic = [dataDic objectForKey:@"downList"];
        NSArray *listsArray5 = [downListDic objectForKey:@"lists"];
        [self.downListArray removeAllObjects];
        [self.downListArray removeAllObjects];
        for (NSDictionary *dic in listsArray5) {
            
            DownList *downList = [[DownList alloc]init];
            [downList setValuesForKeysWithDictionary:dic];
            
            [self.downListArray addObject:downList];
            
        }
        
        NSDictionary *turnoverListDic = [dataDic objectForKey:@"turnoverList"];
        NSArray *listsArray6 = [turnoverListDic objectForKey:@"lists"];
        [self.turnverListArray removeAllObjects];
        for (NSDictionary *dic in listsArray6) {
            
            TurnoverList *turnoverList = [[TurnoverList alloc]init];
            [turnoverList setValuesForKeysWithDictionary:dic];
            
            [self.turnverListArray addObject:turnoverList];
            
        }
        
        //        结束大菊花
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [self.collectionView reloadData];
        [self.collectionView.header endRefreshing];
        
    
    } errorBlock:^(NSError *error) {
        
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络连接错误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        
        [alertView show];
#warning 此处是collectionView不知道行不行
        [self.collectionView.header endRefreshing];

        
        
    }];
    
    
    
    
    
}












- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/





- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    CGSize size = CGSizeMake(300, 21);
    
    return size;
    
}


//设置页眉
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
//    从重用池中取headerview
    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
    
    if (headerView.subviews.count==0) {
        
        UILabel *sectionLabelInit = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, headerView.frame.size.width, headerView.frame.size.height)];
        [headerView addSubview:sectionLabelInit];
    }
    UILabel *sectionLabel=headerView.subviews[0];
    sectionLabel.textAlignment=NSTextAlignmentCenter;

    if (indexPath.section == 0) {
    
        headerView.backgroundColor = MyGrayColor;
        sectionLabel.text = @"深沪大盘";
        return headerView;
    }else if (indexPath.section == 1){
        
        headerView.backgroundColor = MyGrayColor;
        sectionLabel.text = @"热门行业";
        return headerView;
    }else if (indexPath.section == 2){
        
        headerView.backgroundColor = MyGrayColor;
        sectionLabel.text = @"热门概念";
        return headerView;
    }else if (indexPath.section == 3){
        
        headerView.backgroundColor =MyGrayColor
        sectionLabel.text = @"涨幅榜";
        return headerView;
    }else if (indexPath.section == 4){
        
        headerView.backgroundColor = MyGrayColor;
        sectionLabel.text = @"跌幅榜";

        return headerView;
    }else{
        
        headerView.backgroundColor = MyGrayColor;
        

        sectionLabel.text = @"换手率榜";
        return headerView;
    }

    
    return headerView;
}









#pragma mark- UICollectionViewDelegateFlowLayout协议方法 -
#pragma mark - //改变cell大小 -
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        CGSize size1 = CGSizeMake((self.view.bounds.size.width/3), 60);
        
        return size1;
    }else if (indexPath.section == 1||indexPath.section == 2){
        
        CGSize size2 = CGSizeMake((self.view.bounds.size.width/3), 80);
        return size2;
    }else {
        CGSize size3 = CGSizeMake(self.view.bounds.size.width, 40);
        return size3;
    }
    
}


//改变cell距上下左右的距离
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0, 0);
    
}

//改变最小行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    if (section == 0) {
        
        return 0;
    }else if (section == 1||section == 2){
        
        return 0;
    }else{
        
        return 0;
    }
    
    
}

//改变最小列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    
    if (section == 0) {
        
        return 0;
    }else if (section == 1||section == 2){
        
        return 0;
    }else{
        
        return 0;
    }
    

}








#pragma mark <UICollectionViewDataSource>
#pragma mark - 分区 -
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {

    return 6;
}

#pragma mark - 设置一个分区有几个cell -
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
//判断如果是第0，1，2，分区每个分区返回6个cell，否则（4，5，6）返回10个cell
    if (section==0) {

        return self.marketIndexArray.count;
    }
    
    else if (section == 1) {
        return self.hotIndustriesArray.count;
    }else if (section == 2){
        
        return self.hotConceptsArray.count;
    }
    else if (section == 3){
        
        return self.upListArray.count;
    }else if (section == 4){
        
        return self.downListArray.count;
    }else{
        
        return self.turnverListArray.count;
    }
    
}



#pragma mark- cell复用 -
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
         Q1CollectionViewCell *cell1 = [collectionView dequeueReusableCellWithReuseIdentifier:@"Q1" forIndexPath:indexPath];
        cell1.layer.borderColor = [UIColor grayColor].CGColor;
        cell1.layer.borderWidth = 0.5;

        float updown = [cell1.updownLabel.text floatValue];
        
        if (updown>0) {
            cell1.nowPriceLabel.textColor = MyRedColor;
        }else{
            
            cell1.nowPriceLabel.textColor = MyGreenColor;
        }
        
        
        
        cell1.marketIndex = [self.marketIndexArray objectAtIndex:indexPath.item];
        
        return cell1;
        
    }else if (indexPath.section == 1||indexPath.section == 2){
        

//        如果是第一分区，那么要把热门行业的模型赋给cell
       
            Q2CollectionViewCell *cell2 = [collectionView dequeueReusableCellWithReuseIdentifier:@"Q2" forIndexPath:indexPath];
        
        float updownRate = [cell2.updownRateLabel.text floatValue];
        
        if (updownRate>0) {
            
            cell2.updownRateLabel.textColor = MyRedColor;
        }else{
            
            cell2.updownRateLabel.textColor = MyGreenColor;
        }
            cell2.layer.borderColor = [UIColor grayColor].CGColor;
            cell2.layer.borderWidth = 0.5;
        
        if (indexPath.section == 1) {
            cell2.hotIndustries = [self.hotIndustriesArray objectAtIndex:indexPath.item];
            
            
            
            return cell2;
            
        }else{
            
            cell2.hotConcepts = [self.hotConceptsArray objectAtIndex:indexPath.item];
            return cell2;
            
        }
        
    
        
    }else{
        
            Q3CollectionViewCell *cell3 = [collectionView dequeueReusableCellWithReuseIdentifier:@"Q3" forIndexPath:indexPath];
        cell3.layer.borderColor = [UIColor blackColor].CGColor;
        cell3.layer.borderWidth = 0.5;
//        如果是第3分区，把涨幅榜模型赋给cell属性
        if (indexPath.section == 3) {
            
            cell3.upList = [self.upListArray objectAtIndex:indexPath.item];
            float updownRate = [cell3.updownRateLabel.text floatValue];
            
            if (updownRate>0) {
                
                cell3.updownRateLabel.textColor = MyRedColor;
                cell3.nowPriceLabel.textColor = MyRedColor;
            }else{
                cell3.updownRateLabel.textColor = MyGreenColor;
                cell3.nowPriceLabel.textColor = MyGreenColor;
            }
             
            return cell3;
//        如果是第4分区，把跌幅榜模型赋给cell属性
        }else if (indexPath.section == 4){
            cell3.downList = [self.downListArray objectAtIndex:indexPath.item];
            
            float updownRate = [cell3.updownRateLabel.text floatValue];
            
            if (updownRate>0) {
                
                cell3.updownRateLabel.textColor = MyRedColor;
                cell3.nowPriceLabel.textColor = MyRedColor;
            }else{
                cell3.updownRateLabel.textColor = MyGreenColor;
                cell3.nowPriceLabel.textColor = MyGreenColor;
            }
            
            return cell3;
            
//            如果是第五分区，把换手率榜赋给cell属性
        }else{
            
            cell3.turnoverList = [self.turnverListArray objectAtIndex:indexPath.item];
            
            float updownRate = [cell3.updownRateLabel.text floatValue];
            
            if (updownRate>0) {
                
                cell3.updownRateLabel.textColor = [UIColor blackColor];
                cell3.nowPriceLabel.textColor = [UIColor blackColor];
            }else{
                cell3.updownRateLabel.textColor = [UIColor blackColor];
                cell3.nowPriceLabel.textColor = [UIColor blackColor];
            }
            
            
            return cell3;
            
        }
        

        
    }
   

}


//cell被选中方法
#pragma mark- cell被选中方法  -
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
//#warning 需要判断是第几个分区，因为不同分区的cell推出的controller的View是不同的
//    深沪大盘
    if (indexPath.section == 0) {
        MarketIndexDetailTVC *marketIndeDetailTVC = [[MarketIndexDetailTVC alloc]init];
        
        MarketIndex *marketIndex = [[MarketIndex alloc]init];
        marketIndex = [self.marketIndexArray objectAtIndex:indexPath.row];
        self.num = 1;
        self.num = marketIndeDetailTVC.num;
        marketIndeDetailTVC.ID = marketIndex.codeSB;
        marketIndeDetailTVC.idName = marketIndex.name;
        
        [self.navigationController pushViewController:marketIndeDetailTVC animated:YES];
//        热门行业
    }else if (indexPath.section == 1){
        
        HotIndustriesDetailVC *hotIndustriesDetailVC = [[HotIndustriesDetailVC alloc]init];
        HotIndustries *hotindustries = [self.hotIndustriesArray objectAtIndex:indexPath.row];
        hotIndustriesDetailVC.which = YES;
        hotIndustriesDetailVC.ID = hotindustries.idSB;
        [self.navigationController pushViewController:hotIndustriesDetailVC animated:YES];
//        热门概念
    }else if (indexPath.section == 2){
    
        HotIndustriesDetailVC *hotIndustriesDetailVC = [[HotIndustriesDetailVC alloc]init];
        [self.navigationController pushViewController:hotIndustriesDetailVC animated:YES];
        
        HotConcepts *hotConcepts = [self.hotConceptsArray objectAtIndex:indexPath.row];
        hotIndustriesDetailVC.ID = hotConcepts.idSB;
        hotIndustriesDetailVC.which = NO;
//        涨幅榜
    }else if(indexPath.section == 3){
        
        
        StockHomeViewController *stockHome = [[StockHomeViewController alloc]init];
        UpList *upList = self.upListArray[indexPath.row];
        stockHome.stockCode = upList.codeSB;
        stockHome.stockName = upList.name;
        [self.navigationController pushViewController:stockHome animated:YES];
//    跌幅榜
    }else if (indexPath.section == 4){
        
        StockHomeViewController *stockHome = [[StockHomeViewController alloc]init];
        DownList *downList = self.downListArray[indexPath.row];
        stockHome.stockCode = downList.codeSB;
        stockHome.stockName = downList.name;
        [self.navigationController pushViewController:stockHome animated:YES];
//        换手率榜
    }else if (indexPath.section == 5){
        
        StockHomeViewController *stockHome = [[StockHomeViewController alloc]init];
        TurnoverList *turn = self.turnverListArray[indexPath.row];
        stockHome.stockCode = turn.codeSB;
        stockHome.stockName = turn.name;
        [self.navigationController pushViewController:stockHome animated:YES];
        
    }
    
    
    
    
}















#pragma mark <UICollectionViewDelegate>

/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
	return YES;
}
*/

/*
// Uncomment this method to specify if the specified item should be selected
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
*/

/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
	return NO;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	return NO;
}

- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	
}
*/

@end
